// pages/index-cn/index-cn.js
const app = getApp()

Page({
  data: {
    searchValue: '',
    allBooks: [], // 全部合集数据
    filteredBooks: [], // 搜索结果合集
    categories: ['全部', '分级阅读', '桥梁书', '章节书', '其他'],
    currentCategory: '全部',
    sidebarVisible: false,
    currentSidebarItem: 0,
    banners: [
      {
        title: '红火箭分级绘本',
        desc: '科学分级阅读体系，适合各年龄段儿童'
      },
      {
        title: '牛津树系列',
        desc: '全球最受欢迎的儿童英语分级读物'
      },
      {
        title: '典范英语',
        desc: '新版典范英语，全面提升英语能力'
      }
    ],
    recentBooks: [
      { id: 1, count: 30, title: "Jam Jam English", author: "用户1026", coverUrl: "https://dummyimage.com/60x80/ffe066/fff&text=J" },
      { id: 2, count: 20, title: "轻松英语名著", author: "用户1026", coverUrl: "https://dummyimage.com/60x80/ffe066/fff&text=Q" },
      { id: 3, count: 28, title: "Henry and...", author: "用户1026", coverUrl: "https://dummyimage.com/60x80/ffe066/fff&text=H" }
    ],
    recommendBooks: [
      { id: 11, count: 12, title: "一年级", author: "用户1026", coverUrl: "https://dummyimage.com/60x80/ffd54f/fff&text=1" },
      { id: 12, count: 15, title: "二年级", author: "用户1026", coverUrl: "https://dummyimage.com/60x80/ffd54f/fff&text=2" },
      { id: 13, count: 10, title: "三年级", author: "用户1026", coverUrl: "https://dummyimage.com/60x80/ffd54f/fff&text=3" },
      { id: 14, count: 9, title: "四年级", author: "用户1026", coverUrl: "https://dummyimage.com/60x80/ffd54f/fff&text=4" },
      { id: 15, count: 8, title: "五年级", author: "用户1026", coverUrl: "https://dummyimage.com/60x80/ffd54f/fff&text=5" },
      { id: 16, count: 7, title: "六年级", author: "用户1026", coverUrl: "https://dummyimage.com/60x80/ffd54f/fff&text=6" },
      { id: 17, count: 13, title: "七年级", author: "用户1026", coverUrl: "https://dummyimage.com/60x80/ffd54f/fff&text=7" },
      { id: 18, count: 11, title: "八年级", author: "用户1026", coverUrl: "https://dummyimage.com/60x80/ffd54f/fff&text=8" },
      { id: 19, count: 14, title: "九年级", author: "用户1026", coverUrl: "https://dummyimage.com/60x80/ffd54f/fff&text=9" }
    ],
    oxfordBooks: [
      { id: 4, count: 10, title: "牛津树1", author: "用户1001" },
      { id: 5, count: 12, title: "牛津树2", author: "用户1002" },
      { id: 6, count: 15, title: "牛津树3", author: "用户1003" },
      { id: 7, count: 8, title: "牛津树4", author: "用户1004" },
      { id: 8, count: 20, title: "牛津树5", author: "用户1005" },
      { id: 9, count: 18, title: "牛津树6", author: "用户1006" }
    ],
    sidebarItems: [
      { title: '全部', icon: 'icon-book', iconText: '📚' },
      { title: '分级阅读', icon: 'icon-layer', iconText: '📚' },
      { title: '桥梁书', icon: 'icon-bridge', iconText: '🌉' },
      { title: '章节书', icon: 'icon-book-open', iconText: '📖' },
      { title: '其他', icon: 'icon-ellipsis', iconText: '⋯' },
      { title: '阅读计划', icon: 'icon-plus', iconText: '➕' }
    ]
  },

  onLoad() {
    // 加载全部合集数据
    this.loadBooks()
  },

  onShow() {
    // 页面显示时更新数据
    this.loadBooks()
  },

  // 加载书籍数据
  loadBooks() {
    // 模拟网络请求
    wx.showLoading({ title: '加载中...' })
    setTimeout(() => {
      // 模拟网络异常
      const networkError = false // 改为true可测试异常
      if (networkError) {
        wx.hideLoading()
        wx.showToast({ title: '加载失败，请重试', icon: 'none' })
        this.setData({ recentBooks: [], recommendBooks: [] })
        return
      }
      // 正常加载
      wx.hideLoading()
      const globalData = app.globalData
      this.setData({
        recentBooks: globalData.books,
        oxfordBooks: globalData.oxfordBooks,
        allBooks: globalData.books, // 加载全部合集数据
        filteredBooks: globalData.books // 初始化搜索结果
      })
      console.log('loadBooks recentBooks:', this.data.recentBooks)
      console.log('loadBooks oxfordBooks:', this.data.oxfordBooks)
    }, 800)
  },

  // 切换侧边栏
  toggleSidebar() {
    this.setData({
      sidebarVisible: !this.data.sidebarVisible
    })
  },

  // 关闭侧边栏
  closeSidebar() {
    this.setData({
      sidebarVisible: false
    })
  },

  // 分类标签点击
  onCategoryTap(e) {
    const category = e.currentTarget.dataset.category
    this.setData({
      currentCategory: category,
      sidebarVisible: false // 选中后自动关闭抽屉
    })
    // 可在此处根据分类筛选推荐合集等
    // this.filterBooksByCategory(category)
  },

  // 根据分类筛选书籍
  filterBooksByCategory(category) {
    const globalData = app.globalData
    let filteredBooks = []
    
    if (category === '全部') {
      filteredBooks = globalData.books
    } else {
      filteredBooks = globalData.books.filter(book => book.category === category)
    }
    // 不再 setData recentBooks，只保留分类切换逻辑
    // this.setData({
    //   recentBooks: filteredBooks
    // })
    // 可根据需要 setData 其他内容
    console.log('filterBooksByCategory:', category, filteredBooks)
  },

  // 侧边栏项目点击
  onSidebarItemTap(e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      currentSidebarItem: index,
      sidebarVisible: false
    })
    
    // 根据侧边栏选择更新分类
    const item = this.data.sidebarItems[index]
    if (item.title !== '阅读计划') {
      this.setData({
        currentCategory: item.title
      })
      this.filterBooksByCategory(item.title)
    } else {
      // 处理阅读计划
      this.createPlan()
    }
  },

  // 书籍点击
  onBookTap(e) {
    const book = e.currentTarget.dataset.book
    wx.navigateTo({
      url: `/pages/detail/detail?id=${book.id}&title=${book.title}`
    })
  },

  // 轮播图点击
  onBannerTap(e) {
    const index = e.currentTarget.dataset.index
    const banner = this.data.banners[index]
    
    wx.showToast({
      title: `查看${banner.title}`,
      icon: 'none'
    })
  },

  // 搜索功能
  onSearchInput(e) {
    const value = e.detail.value.trim()
    this.setData({ searchValue: value })
    this.filterBooks(value)
  },
  onSearch() {
    this.filterBooks(this.data.searchValue)
  },
  filterBooks(value) {
    if (!value) {
      this.setData({ filteredBooks: this.data.allBooks })
      return
    }
    // 支持拼音/汉字模糊搜索
    const filtered = this.data.allBooks.filter(item =>
      item.title.includes(value) || item.author.includes(value)
    )
    this.setData({ filteredBooks: filtered })
  },

  // 创建阅读计划
  createPlan() {
    wx.showModal({
      title: '创建阅读计划',
      content: '确定要创建新的阅读计划吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '计划创建成功',
            icon: 'success'
          })
        }
      }
    })
  },

  // 磨耳朵按钮点击
  goEarModule() {
    wx.navigateTo({
      url: '/pages/audio-list/audio-list'
    })
  },

  onClearRecent() {
    const that = this
    wx.showModal({
      title: '清空最近阅读',
      content: '是否清空最近阅读记录？',
      success(res) {
        if (res.confirm) {
          that.setData({ recentBooks: [] })
          wx.showToast({ title: '已清空', icon: 'success' })
        }
      }
    })
  },

  // 页面分享
  onShareAppMessage() {
    return {
      title: '中文书架 - 儿童分级阅读',
      path: '/pages/index-cn/index-cn'
    }
  }
}) 